<script>
import OSS from 'ali-oss'
import { getSocket, initWebSocket } from '@/utils/ws'
import config from '@/config'
import { isLoggedIn } from '@/utils/auth'
export default {
	data() {
		return {
			wsTimer: null, // 用于存储心跳定时器ID
		}
	},
	// 初始化应用数据、获取启动参数、检查更新等
	onLaunch: function () {
		if (!this.isWechat()) {
			console.log('App-onLaunch', '不是微信环境');
		} else {
			console.log('是微信环境');
			const urlParams = new URLSearchParams(window.location.search);
			const code = urlParams.get('code');
			console.log(123, '微信环境获取URL参数code', code, urlParams);
			let hasOpenId = uni.getStorageSync('openId');
			const newUrl = window.location.origin + window.location.pathname;
			console.log("新url:",newUrl);
			if (code) {
				window.history.replaceState({},document.title,newUrl)
				if(!hasOpenId){
					if (!isLoggedIn()) {
						this.$http.get(`/applet/customer/wxLogin/${code}`).then(res => {
							//console.log(123, '/applet/customer/wxLogin/', res);
							// res.data //  .isLogin  .loginInfo .openId
							if (res.data && res.data.openId) {
								uni.setStorageSync('openId', res.data.openId)
							}
							if (res.data && res.data.loginInfo) {
								uni.setStorageSync('token', res.data.loginInfo.token)
								uni.setStorageSync('customerInfo', res.data.loginInfo)
							}
						})
					}
				}
				
			} else {
				if(!hasOpenId){
					this.wechatLogin();
				}
			}
		}
		this.getAppletConfig();
	},
	// 刷新数据、重新建立连接、检查登录状态等
	onShow: function () {
		console.log('App-onShow');

		// 获取阿里云oss临时stsToken
		if (uni.getStorageSync('stsToken')) {
			// 如果stsToken存在，则设置过期时间
			uni.setStorageSync('stsTokenExpiration', uni.getStorageSync('stsToken').expiration)
			// 如果过期时间小于当前时间，则重新获取stsToken
			if (this.$moment(uni.getStorageSync('stsTokenExpiration')).valueOf() < Date.now()) {
				this.getSts()
			}
		} else {
			this.getSts()
		}

		// 页面刷新之后立即执行一次WS处理
		this.wsTimerDo();

		// 每个五秒钟 发送一次心跳数据
		// if (!this.wsTimer) {
		// 	this.wsTimer = setInterval(() => {
		// 		this.wsTimerDo();
		// 	}, 20000)
		// }
	},
	// 暂停定时器、保存数据、断开连接等
	onHide: function () {
	},
	// 清理资源、清除定时器、断开连接等
	onUnload() {
		// 页面卸载时清除定时器
		if (this.wsTimer) {
			clearInterval(this.wsTimer);
			this.wsTimer = null;
		}
	},
	globalData: {
		client: null
	},
	methods: {
		// 心跳数据定时器
		wsTimerDo() {
			// 获取socket对象
			let socket = getSocket();
			// 页面刷新之后，原有的socket对象已经失效，需要重新建立连接
			if (!socket || socket.readyState !== 1) {
				initWebSocket();
			}
		},
		getSts() {
			this.$http.get('/aliyun/config/getSts').then(res => {
				uni.setStorageSync('stsToken', res.data)
			})
		},

		// 获取全局数据
		getGlobalData() {
			return this.globalData
		},

		// 获取OSS客户端
		getOSSClient() {
			return this.globalData.client = new OSS({
				region: uni.getStorageSync('stsToken').regionId, // 上传后的域名	
				accessKeyId: uni.getStorageSync('stsToken').accessKeyId, // 后台的临时签名ID
				accessKeySecret: uni.getStorageSync('stsToken').accessKeySecret, // 后台的临时签名密钥
				stsToken: uni.getStorageSync('stsToken').securityToken,
				bucket: uni.getStorageSync('stsToken').bucketName, // OSS仓库名
			});
		},
		// 是否是微信环境
		isWechat() {
			// #ifdef H5
			const ua = (typeof navigator !== 'undefined' && navigator.userAgent) ? navigator.userAgent.toLowerCase() : '';
			return ua.indexOf('micromessenger') !== -1;
			// #endif
			// #ifndef H5
			return false;
			// #endif
		},
		// 一键登录获取code
		async wechatLogin() {
			console.log('一键登录获取code');
			const appId = config.wechatConfig.wechatAppId;
			let redirectUri = encodeURIComponent(window.location.href); 
			const state = 'STATE';
			const scope = 'snsapi_userinfo';
			const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
			window.location.href = authUrl;
		},
		async getAppletConfig(){
			this.$http.get('/applet/config/getAppletConfig').then(res => {
				uni.setStorageSync('appletConfig', res.data)
			})
		}
	}
}
</script>

<style>
/*每个页面公共css */
uni-page-head {
	display: none;
}
.pages-order-index {
	overflow: hidden;
}

/* 调整 uni-nav-bar 左侧/按钮容器默认宽度为 60rpx */
.uni-navbar__header-btns,
.uni-navbar__header-btns-left {
	width: 200rpx !important;
	flex: 0 0 200rpx !important;
}
</style>
